<template>
  <u-image :src="localPath" :width="width" :height="height" :border-radius="radius" @error="tryDownload" :lazy-load="lazyLoad" :fade="false" :mode="mode"
    @tap="sendTap"  :duration="80"
  >
    <u-image slot="error" :src="src" :width="width" :height="height" :border-radius="radius"></u-image>
    <u-loading slot="loading"></u-loading>
  </u-image>
</template>

<script>
  import md5 from 'md5'
  export default {
    name:"static-image",
    props: {
      width: {
        type: Number,
        default: 90
      },
      height: {
        type: Number,
        default: 90
      },
      radius: {
        type: Number,
        default: 10
      },
      src: {
        type: String,
        default: ''
      },
      lazyLoad: {
        type: Boolean,
        default: false
      },
      mode: {
        type: String,
        default: 'aspectFill'
      }
    },
    data() {
      const plat = uni.getSystemInfoSync().uniPlatform;
      const urlMd5 = md5(this.src)
      let path = plat === 'web' ? this.src : (uni.getStorageSync('l_' + urlMd5) || 'wait load')
      return {
        urlMd5,
        plat,
        localPath: path
      };
    },
    created () {
      this.$watch(() => this.src, () => {
        if (this.plat === 'web') {
          this.localPath = this.src
          return
        }
        this.urlMd5 = md5(this.src)
        this.localPath = uni.getStorageSync('l_' + this.urlMd5) || 'wait load'
      })
    },
    methods: {
      sendTap () {
        this.$emit('on-tap')
      },
      async tryDownload (e) {
        if (this.plat === 'web') return
        console.log('errrrrr', e, this.localPath)
        const tempFilePath = await new Promise((resolve, reject) => {
          uni.downloadFile({
            url: this.src,
            success: (res) => {
              console.log('res:', res)
              if (res.statusCode === 200) {
                resolve(res.tempFilePath) 
              } else {
                reject('err1:'+this.src)
              }
            },
            fail () {
              reject('err2')
            }
          })
        })
        
        uni.saveFile({
          tempFilePath: tempFilePath,
          success: (res) => {
            console.log(res)
            uni.setStorage({
              data: res.savedFilePath,
              key: `l_${this.urlMd5}`
            })
          }
        })
      }
    }
  }
</script>

<style>

</style>